
var kitkatApp = angular.module('kitkatApp',['ngTouch','ngFileUpload','ngDialog','ngAlert']);

//设置http拦截器
kitkatApp.factory('frameInterceptor',function($window,$q,$injector) {
    var interceptor = {
        "request" : function(config) {
            return config;
        },
        "response" : function(response) {
        	//var status = response.status;
        	var res = response.data;
        	if(res.isError) {
        		var code = res.errorCode;
        		$injector.get("ngAlert").Alert(res.errorMsg,function() {
        			if(code == 401) {
            			$window.location.href = "pageLogin.do";
            		}
        		});
        		return $q.reject(response);
        	}
            return response;
        },
        "requestError" : function(response) {
            return response;
        },
        "responseError" : function(response) {
            var status = response.status;
            if(status == 401) {
                $window.location.href = "pageLogin.do";
            }
            return $q.reject(response);
        }
    };
    return interceptor;
});


kitkatApp.config(['$httpProvider',function($httpProvider) {
	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
	$httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
	$httpProvider.defaults.headers.common['request_type'] = "ajax";
	$httpProvider.interceptors.push('frameInterceptor');
}]);

//元素可拖动和修改大小
kitkatApp.directive('edit', function() {
	return {
        restrict : 'EA',
        link : function($scope, element) {
        	//获取鼠标当前位置
        	function mouseCoords(ev) { 
	        	if(ev.pageX || ev.pageY){ 
	        	    return {x:ev.pageX, y:ev.pageY}; 
	        	} 
        	    return{ 
		        	x:ev.clientX + document.body.scrollLeft - document.body.clientLeft, 
		        	y:ev.clientY + document.body.scrollTop - document.body.clientTop 
        	    }; 
        	} 
        	
        	//画板所在屏幕中的位置
        	/*offsetLeft = $("#canvas")[0].offsetLeft + $("#leftframe").width();
			offsetTop = $("#canvas")[0].offsetTop + $("header").height();*/
        	
        	//鼠标移入元素,随着位置鼠标样式发生变化,靠近边缘则能调节大小
    		$(element).bind("mousemove",function(ev) {
    			var mousePos = mouseCoords(ev);
    			//鼠标点击时距离元素左上角位置
    			var mouseLocLeft = Math.abs(mousePos.x - offsetLeft - $(this).width()*scale - $(this).css("left").replace("px","")*scale);
    			var mouseLocTop = Math.abs(mousePos.y - offsetTop - $(this).height()*scale - $(this).css("top").replace("px","")*scale);
    			if(mouseLocLeft < 10 && mouseLocTop > 10) {
        			$(this).css("cursor","e-resize");
        		}else if(mouseLocLeft > 10 && mouseLocTop < 10){
        			$(this).css("cursor","s-resize");
        		}else if(mouseLocLeft < 10 && mouseLocTop < 10){
        			$(this).css("cursor","se-resize");
        		}else{
        			$(this).css("cursor","move");
        		}
    		});
        	
        	//鼠标点下元素
    		var target = "";
        	$(element).bind("mousedown",function(ev) {
        		target = this;
        		//获取鼠标当前位置
        		var mousePos = mouseCoords(ev);
        		//获取鼠标点下时所在元素的位置
    			var prePosition = {};
    			prePosition.left = mousePos.x - offsetLeft - $(target).css("left").replace("px","")*scale;
    			prePosition.top = mousePos.y - offsetTop - $(target).css("top").replace("px","")*scale;
    			
    			var selectele = $scope.selectEle.ele;
    			//鼠标点击时距离元素左上角位置
    			var mouseLocLeft = Math.abs(mousePos.x - offsetLeft - $(target).width()*scale - $(target).css("left").replace("px","")*scale);
    			var mouseLocTop = Math.abs(mousePos.y - offsetTop - $(target).height()*scale - $(target).css("top").replace("px","")*scale);
    			if(mouseLocLeft < 10 && mouseLocTop > 10) {//向右拖动
    				//绑定鼠标移动事件
        			$(document).bind("mousemove",function(ev){
                		if(target) {
                			$(target).css("cursor","e-resize");
                			var mousePos = mouseCoords(ev);
                			var width = (mousePos.x - offsetLeft)/scale - $(target).css("left").replace("px","") + 5/scale;
                			$(target).css("width",width);
                			selectele.style.width = width;
                            $scope.$apply();
                		}
            		});
        		}else if(mouseLocLeft > 10 && mouseLocTop < 10){//向下拖动
        			//绑定鼠标移动事件
        			$(document).bind("mousemove",function(ev){
                		if(target) {
                			$(target).css("cursor","s-resize");
                			var mousePos = mouseCoords(ev);
                			var height = (mousePos.y - offsetTop)/scale - $(target).css("top").replace("px","") + 5/scale;
                			console.log(height);
                			$(target).css("height",height);
                			selectele.style.height = height;
                            $scope.$apply();
                		}
            		});
        		}else if(mouseLocLeft < 10 && mouseLocTop < 10){//向右下方拖动
        			//绑定鼠标移动事件
        			$(document).bind("mousemove",function(ev){
                		if(target) {
                			$(target).css("cursor","se-resize");
                			var mousePos = mouseCoords(ev);
                			var height = (mousePos.y - offsetTop)/scale - $(target).css("top").replace("px","") + 5/scale;
                			var width = (mousePos.x - offsetLeft)/scale - $(target).css("left").replace("px","") + 5/scale;
                			$(target).css("width",width);
                			$(target).css("height",height);
                			selectele.style.width = width;
                			selectele.style.height = height;
                            $scope.$apply();
                		}
            		});
        		}else if(mouseLocLeft > 10 && mouseLocTop > 10){//移动
        			$(document).bind("mousemove",function(ev){
                		if(target) {
                			$(target).css("cursor","move");
                			var mousePos = mouseCoords(ev);
                			var left = ( (mousePos.x - offsetLeft) - prePosition.left ) / scale;
                			var Top = ( (mousePos.y - offsetTop) - prePosition.top ) / scale;
                			$(target).css("left",left);
                			$(target).css("top",Top);
                			selectele.style.left = left;
                            selectele.style.top = Top;
                            $scope.$apply();
                		}
            		});
        		}
    			
    			$(document).bind("mouseup",function(){
        			$(document).unbind("mousemove");
        			target = "";
        		});
    			
    			
        	});
        }
    }
});

//元素能调整位置
kitkatApp.directive('sortable', function() {
    return {
        restrict : 'EA',
        link : function($scope, element ) {
          $(element).sortable({
              stop: function( event, ui ) {
                 $("ul li .number").each(function(index) {
                     var pageId = $(this).parent().attr("id");
                     var length = $scope.pages.length;

                     for(var i=0;i<length;i++) {
                        if(pageId == $scope.pages[i].pageId) {

                            $scope.pages[i].index = index+1;
                            break;
                        }
                     }
                 });

                 $scope.$parent.$apply();
              },
               axis: "y",cursor: "move", containment: "parent"
            });
        }
    }
});

//元素带滚动条
kitkatApp.directive('scroll', function() {
	return {
        restrict : 'EA',
        link : function(scope, element ) {
          $(element).niceScroll({cursorwidth :"10px",cursorcolor:"grey"});
        }
    }
});

//滑条
kitkatApp.directive('slider', function() {
    return {
        restrict : 'EA',
        link : function($scope, element,attrs) {
          var type = attrs.type;
          $(element).draggable({containment:"parent",
            drag:function(event,ui){
                var scope = $scope.$parent;
                var selectele = $scope.selectEle.ele;
                switch (type){
                    case "opacity":
                      var opacity = event.target.style.left.replace("px","")/120;
                      selectele.style.opacity = opacity.toFixed(2);
                      break;
                    case "rotate":
                      var rotate = event.target.style.left.replace("px","")/120*360;
                      selectele.style.rotate = rotate;
                      selectele.style.webkitTransform = "rotate(" + rotate + "deg)";
                      break;
                    case "boxShadow":
                      var boxShadowWidth = event.target.style.left.replace("px","")/120*100;
                      selectele.style.boxShadowWidth = boxShadowWidth.toFixed(2);
                      selectele.style.boxShadow = "0 0 " + boxShadowWidth + "px #000";
                      break;
                    case "borderRadius":
                      var borderRadius = event.target.style.left.replace("px","")/120*100;
                      selectele.style.borderRadius = parseInt(borderRadius.toFixed(2));
                      console.log(selectele.style);
                      break;
                    case "animateTime":
                      var animateTime = event.target.style.left.replace("px","")/120*10;
                      selectele.style.animateTime = animateTime.toFixed(2);
                      selectele.style.webkitAnimationDuration = animateTime + "s";
                      break;
                    case "animateDelay":
                      var animateDelay = event.target.style.left.replace("px","")/120*10;
                      selectele.style.animateDelay = animateDelay.toFixed(2);
                      selectele.style.webkitAnimationDelay = animateDelay + "s";
                      break;
                    case "backImgopacity":
                      var backImgopacity = event.target.style.left.replace("px","")/120;
                      scope.page.backImg.style.opacity = backImgopacity.toFixed(2);
                      break;
                }
                $scope.$parent.$apply();
            }
          });
        }
    }
});

//元素右击菜单
kitkatApp.directive('elemenu', function() {
	return {
        restrict : 'EA',
        link : function(scope, element ) {
        	var $scope = scope;
        	$.contextMenu({
      	        selector: 'div[edit]', 
      	        callback: function(key, options) {
      	        	var id = $(this).attr("id");
      	        	$scope.selectEle.id = id;
      	        	var length = $scope.page.eles.length;
      	        	for(var i=0;i<length;i++) {
      	        		var ele = $scope.page.eles[i];
      	        		if(ele.id == id) {
      	        			$scope.selectEle.ele = ele;//被选中的元素
      	        		}
      	        	}
      	        	switch (key) {
      	              case "copy" :
      	            	  $scope.copy = $scope.selectEle.ele;
      	            	  break;
      	              case "up" :
      	            	  $scope.selectEle.ele.style.zIndex++;
    	            	  break;
      	              case "down" :
      	            	 $scope.selectEle.ele.style.zIndex++;
  	            	     break;
      	               case "top" :
      	            	 $scope.selectEle.ele.style.zIndex = 1000;
    	            	  break;
      	               case "bottom":
      	            	 $scope.selectEle.ele.style.zIndex = 0;
  	            	      break;
      	               case "delete":
      	            	var length = $scope.page.eles.length;
           	        	for(var i=0;i<length;i++) {
           	        		var ele = $scope.page.eles[i];
           	        		if(ele.id == id) {
           	        			$scope.page.eles.splice(i,1);
           	        		}
           	        	}
 	            	    break;
      	            }
      	        	$scope.$apply();
      	        },
      	        items: {
      	            "copy": {name: "复制", icon: "", accesskey: "e"},
      	            "up": {name: "上移一层", icon: "", accesskey: "c"},
      	            "down": {name: "下移一层", icon: "", accesskey: "c o p y"},
      	            "top": {name: "置顶", icon: "", accesskey: "cool paste"},
      	            "bottom": {name: "置底", icon: ""},
      	            "delete": {name: "删除", icon: ""}
      	        }
      	    });
        }
    }
});

//元素右击菜单
kitkatApp.directive('backmenu', function(UUID) {
	return {
        restrict : 'EA',
        link : function(scope, element ) {
        	var $scope = scope;
        	$.contextMenu({
      	        selector: '#centerframe .backImg', 
      	        callback: function(key, options) {
      	        	switch (key) {
      	              case "paste" :
      	            	  var newEle = {};
      	            	  var str = JSON.stringify($scope.copy);
      	            	  var copy = eval("("+str+")");
      	            	  for(key in copy) {
      	            		if(key != "$$hashKey") {
      	            			newEle[key] = copy[key];
      	            		} 
      	            	  }
      	            	  newEle.id = UUID.getUUID();
      	            	  $scope.page.eles.push(newEle);
      	            	  $scope.selectEle.ele = "";
      	            	  $scope.selectEle.id = "";
      	            	  break;
      	            }
      	        	$scope.$apply();
      	        	$("div[edit]").one("webkitAnimationEnd",function(){//去掉动画的样式才可以修改透明度和旋转等样式
      	                $(this).removeClass();
      	            });
      	        },
      	        items: {
      	            "paste": {name: "粘贴", icon: "", accesskey: "v"}
      	        }
      	    });
        }
    }
});


//图片截取
kitkatApp.directive('jcrop', function() {
    return {
        restrict : 'EA',
        link : function($scope, element ) {
            var setChange = function (c){
                  var x = c.x;
                  var y = c.y;
                  var x2 = c.x2;
                  var y2 = c.y2;
                  var width = c.w;
                  var height = c.h;

                  var times = 150/width;
                  var timesx = x/150;
                  var timesy = y/235;
                  var style = $scope.$parent.page.backImg.style;
                  style.width = 300*times;
                  style.height = 470*times;
                  style.left = -style.width*timesx;
                  style.top = -style.height*timesy;
                  $scope.$parent.$apply();
            }
            $(element).Jcrop({
              onChange:setChange,
              onSelect:setChange,
              aspectRatio:0.638
            },function(){
              $scope.$parent.jcrop = this;
            });
        }
    }
});

//二维码生成
kitkatApp.directive('qcode', function() {
    return {
        restrict : 'EA',
        link : function($scope, element ,attr) {
           var url = attr.url;
	       $(element).qrcode({width: 200,height: 150,text: url});
        }
    }
});